<template>
  <el-dialog v-model="dialogVisible" title="表单预览" width="900px" top="5vh">
    <el-form
      ref="previewFormRef"
      :model="formData"
      :label-width="labelWidth"
      :label-position="labelPosition"
      class="preview-form"
    >
      <!-- 遍历表单元素进行渲染 -->
      <div v-for="item in formItems" :key="item.id" class="preview-item">
        <!-- 章节标题 -->
        <div v-if="item.type === 'section'" class="section-preview" :style="getSectionStyle(item)">
          {{ item.options.title }}
        </div>

        <!-- 文本段落 -->
        <div
          v-else-if="item.type === 'paragraph'"
          class="paragraph-preview"
          :style="getParagraphStyle(item)"
        >
          {{ item.options.content }}
        </div>

        <!-- 分割线 -->
        <el-divider v-else-if="item.type === 'divider'" />

        <!-- 签名区域 -->
        <div v-else-if="item.type === 'signature'" class="signature-preview">
          <div class="signature-label">{{ item.options.label }}</div>
          <div class="signature-area">
            <div class="signature-line"></div>
          </div>
        </div>

        <!-- 常规表单元素 -->
        <el-form-item
          v-else
          :label="item.options.label"
          :prop="item.model"
          :rules="getValidationRules(item)"
        >
          <!-- 输入框 -->
          <el-input
            v-if="item.type === 'input'"
            v-model="formData[item.model]"
            :placeholder="item.options.placeholder"
            :maxlength="item.options.maxLength"
            :show-word-limit="!!item.options.maxLength"
          />

          <!-- 文本域 -->
          <el-input
            v-else-if="item.type === 'textarea'"
            v-model="formData[item.model]"
            type="textarea"
            :placeholder="item.options.placeholder"
            :rows="item.options.rows"
          />

          <!-- 数字输入 -->
          <el-input-number
            v-else-if="item.type === 'number'"
            v-model="formData[item.model]"
            :placeholder="item.options.placeholder"
            :min="item.options.min"
            :max="item.options.max"
            style="width: 100%"
          />

          <!-- 下拉选择 -->
          <el-select
            v-else-if="item.type === 'select'"
            v-model="formData[item.model]"
            :placeholder="item.options.placeholder"
            style="width: 100%"
          >
            <el-option
              v-for="option in item.options.options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>

          <!-- 单选框组 -->
          <el-radio-group v-else-if="item.type === 'radio'" v-model="formData[item.model]">
            <el-radio
              v-for="option in item.options.options"
              :key="option.value"
              :label="option.value"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>

          <!-- 多选框组 -->
          <el-checkbox-group v-else-if="item.type === 'checkbox'" v-model="formData[item.model]">
            <el-checkbox
              v-for="option in item.options.options"
              :key="option.value"
              :label="option.value"
            >
              {{ option.label }}
            </el-checkbox>
          </el-checkbox-group>

          <!-- 日期选择 -->
          <el-date-picker
            v-else-if="item.type === 'date'"
            v-model="formData[item.model]"
            type="date"
            :placeholder="item.options.placeholder"
            :format="item.options.format"
            style="width: 100%"
          />

          <!-- 开关 -->
          <el-switch v-else-if="item.type === 'switch'" v-model="formData[item.model]" />
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'FormPreview',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    formItems: {
      type: Array,
      default: () => [],
    },
    formConfig: {
      type: Object,
      default: () => ({
        labelWidth: '100px',
        labelPosition: 'right',
      }),
    },
  },
  emits: ['update:visible'],
  setup(props, { emit }) {
    const dialogVisible = computed({
      get: () => props.visible,
      set: (value) => emit('update:visible', value),
    })

    const previewFormRef = ref(null)
    const formData = ref({})
    const labelWidth = ref(props.formConfig.labelWidth || '100px')
    const labelPosition = ref(props.formConfig.labelPosition || 'right')

    // 初始化表单数据 - 必须先定义这个函数
    const initializeFormData = (items) => {
      const data = {}
      items.forEach((item) => {
        if (item.model && !['section', 'paragraph', 'divider'].includes(item.type)) {
          // 设置默认值
          if (item.type === 'checkbox') {
            data[item.model] = item.options.defaultValue || []
          } else if (item.type === 'switch') {
            data[item.model] = item.options.defaultValue || false
          } else if (item.type === 'number') {
            data[item.model] = item.options.defaultValue || 0
          } else {
            data[item.model] = item.options.defaultValue || ''
          }
        }
      })
      formData.value = data
    }

    // 获取验证规则
    const getValidationRules = (item) => {
      if (!item.options.required) return []

      return [
        {
          required: true,
          message: `请输入${item.options.label}`,
          trigger: item.type === 'checkbox' ? 'change' : 'blur',
        },
      ]
    }

    // 获取章节标题样式
    const getSectionStyle = (item) => {
      const level = item.options.level || 2
      const styles = {
        fontWeight: 'bold',
        margin: '20px 0 10px 0',
        color: '#303133',
      }

      if (level === 1) {
        styles.fontSize = '24px'
        styles.borderBottom = '2px solid #409eff'
        styles.paddingBottom = '8px'
      } else if (level === 2) {
        styles.fontSize = '20px'
        styles.borderLeft = '4px solid #409eff'
        styles.paddingLeft = '12px'
      } else {
        styles.fontSize = '16px'
      }

      return styles
    }

    // 获取段落样式
    const getParagraphStyle = (item) => {
      return {
        lineHeight: '1.6',
        margin: '10px 0',
        color: '#606266',
        padding: '8px 12px',
        backgroundColor: '#f8f9fa',
        borderRadius: '4px',
      }
    }

    // 处理表单提交
    const handleSubmit = async () => {
      if (!previewFormRef.value) return

      try {
        // 验证表单
        await previewFormRef.value.validate()

        // 检查必填项
        const requiredItems = props.formItems.filter(
          (item) =>
            item.options.required &&
            !['section', 'paragraph', 'divider', 'signature'].includes(item.type),
        )

        const missingFields = requiredItems.filter((item) => {
          const value = formData.value[item.model]
          if (item.type === 'checkbox') {
            return !value || value.length === 0
          }
          return !value && value !== 0 && value !== false
        })

        if (missingFields.length > 0) {
          ElMessage.error('请填写所有必填字段')
          return
        }

        ElMessage.success('表单提交成功！')
        console.log('表单数据:', formData.value)
        dialogVisible.value = false
      } catch (error) {
        ElMessage.error('请检查表单填写是否正确')
      }
    }

    // 监听表单项变化，初始化表单数据 - 现在这个watch放在所有函数定义之后
    watch(
      () => props.formItems,
      (newItems) => {
        initializeFormData(newItems)
      },
      { immediate: true, deep: true },
    )

    return {
      dialogVisible,
      previewFormRef,
      formData,
      labelWidth,
      labelPosition,
      getValidationRules,
      getSectionStyle,
      getParagraphStyle,
      handleSubmit,
    }
  },
}
</script>

<style scoped>
.preview-form {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.preview-item {
  margin-bottom: 16px;
}

.section-preview {
  font-weight: bold;
  margin: 20px 0 10px 0;
  color: #303133;
}

.paragraph-preview {
  line-height: 1.6;
  margin: 10px 0;
  color: #606266;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.signature-preview {
  margin: 20px 0;
  text-align: center;
}

.signature-label {
  margin-bottom: 10px;
  font-weight: bold;
  color: #606266;
}

.signature-area {
  min-height: 100px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}

.signature-line {
  width: 200px;
  height: 2px;
  background-color: #dcdfe6;
  margin: 0 auto;
}

.preview-form .el-form-item {
  margin-bottom: 22px;
}

:deep(.el-dialog__body) {
  padding: 0;
}
</style>
